<?php
/**
 *
 * User:xinhuazhang
 * Date:2024/5/7
 * TIPS:功能说明
 * Email:<1655626823@qq.com>
 */

namespace app\api\controller;

use app\admin\model\Houses as HousesModel;
use app\common\controller\Frontend;
use app\common\model\UserCollect;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\exception\ValidateException;
use think\facade\App;

#[Apidoc\Title("找店铺管理")]
class Findstore extends Frontend
{
    protected array $noNeedPermission = ['*'];

    #[
        Apidoc\Title("我发布的找店铺列表"),
        Apidoc\Tag("name	标题
create_time	添加时间
update_time	创建时间
status	状态:0=禁用,1=启用
user_id	所属用户
start_area	面积范围
end_area	面积范围
start_rent	租金范围
end_rent	租金范围
rent_unit	租金单位:0=元/月,1=元/㎡/月
weigh	权重
reward	悬赏佣金
city	城市选择
introduction	介绍
address	详情地址"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/Findstore/index"),
        Apidoc\Query(name: "page", type: "number", require: false, desc: "页码", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
    ]
    public function index()
    {
        $page = input('page', 1);
        $where = [];
        //$where[] = ['status', '=', 1];
        $where[] = ['user_id', '=', $this->auth->id];
        $list = \app\common\model\Findstore::where($where)->order('id', 'desc')
            ->paginate()
            ->each(function ($item) {
                $order_row = (new \app\common\model\Orders())->order('id', 'desc')->where([
                    'house_id' => $item['id'],
                    'user_id' => $this->auth->id,
                    'house_type' => 'findstore'
                ])->find();
                $item['pay_status'] = $order_row ? $order_row['pay_status'] : 0;//支付状态:0=待支付,1=支付成功,2=已退款
                if ($order_row) {
                    $item['payed_day'] = (time() - $order_row['paid_time']) / (3600 * 24);
                } else {
                    $item['payed_day'] = 0;
                }

                $item['dealer_info'] = '';
                if ($item['status'] == 4) {
                    $dealer_id = (new \app\admin\model\Orders())
                        ->where('id', $item['order_id'])
//                ->where([
//                    'house_id' => $result['id'],
//                    'pay_status' => ['in', [1,3]],
//                    'house_type' => 'findstore'
//                ])
                        ->value('to_uid');
                    $item['dealer_info'] = (new \app\admin\model\User())->where(['id' => $dealer_id])->find();
                }
            });
        $this->success('获取成功', $list);
    }

    #[
        Apidoc\Title("我发布的添加找店铺 新版本3.0"),
        Apidoc\Tag("name	标题
                is_vip 是否是vip  0否1是
        view_price单次查看价格
start_area	面积范围
end_area	面积范围
start_rent	租金范围
end_rent	租金范围
rent_unit	租金单位:0=元/月,1=元/㎡/月
reward	悬赏佣金
city	城市选择(1,2,3)
introduction	介绍
address	详情地址"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/Findstore/add"),
        Apidoc\Query(name: "industry_pid", type: "number", require: false, desc: "一级行业", mock: "1"),
        Apidoc\Query(name: "industry", type: "数组", require: false, desc: "二级行业", mock: "1"),

        Apidoc\Query(name: "city", type: "数组", require: false, desc: "期望地区选择(1,2,3)", mock: "1"),
        Apidoc\Query(name: "start_area", type: "number", require: false, desc: "面积范围", mock: "1"),
        #Apidoc\Query(name: "end_area", type: "number", require: false, desc: "面积范围", mock: "1"),
        Apidoc\Query(name: "start_rent", type: "number", require: false, desc: "租金范围", mock: "1"),
        #Apidoc\Query(name: "end_rent", type: "number", require: false, desc: "租金范围", mock: "1"),
        #Apidoc\Query(name: "rent_unit", type: "number", require: false, desc: "租金单位:0=元/月,1=元/㎡/月", mock: "1"),

        Apidoc\Query(name: "contact_person", type: "字符串", require: false, desc: "联系人", mock: "1"),
        Apidoc\Query(name: "reward", type: "number", require: false, desc: "悬赏佣金", mock: "1"),
        #Apidoc\Query(name: "introduction", type: "number", require: false, desc: "具体要求", mock: "1"),
        #Apidoc\Query(name: "address", type: "number", require: false, desc: "详情地址", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id返回房源id 用于支付佣金"),
    ]
    public function add()
    {
        $data = $this->request->post();
        $data["user_id"] = $this->auth->id;
        $data["status"] = 1;
        $data["name"] = "找房";
        $data["create_time"] = time();
        $result = \app\common\model\Findstore::create($data);
        try {
            validate(\app\admin\validate\Findstore::class)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $this->error($e->getError());
        }
        if ($result) {
            $role_type = \app\common\model\User::where('id', $this->auth->id)->value('role_type');
            if (!empty($role_type)) {
                $role_type = explode(',', $role_type);
                if (!in_array(2, $role_type)) {
                    $role_type[] = 2;
                } else {
                    $role_type = '';
                }
            } else {
                $role_type = [2];
            }
            if ($role_type) {
                (new \app\admin\model\User())
                    ->where('id', $this->auth->id)
                    ->update([
                        'role_type' => implode(',', $role_type)
                    ]);
            }
            $this->success('发布成功', [
                'id' => $result->id
            ]);
        } else {
            $this->error('发布失败');
        }
    }

    #[
        Apidoc\Title("我发布的编辑找店铺（上下架）"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/Findstore/edit"),
        Apidoc\Query(name: "id", type: "number", require: true, desc: "找点ID", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
    ]
    public function edit()
    {
        $data = $this->request->post();
        $id = $data['id'];
        $result = \app\common\model\Findstore::update($data, ['id' => $id]);
        if ($result) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    #[
        Apidoc\Title("删除找店铺"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/Findstore/delete"),
        Apidoc\Query(name: "id", type: "number", require: true, desc: "找点ID", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
    ]
    public function delete()
    {
        $id = $this->request->post('id');
        $result = \app\common\model\Findstore::where(['id' => $id, 'user_id' => $this->auth->id])->find();
        if (!$result) {
            $this->error('找不到数据');
        }
        $order_row = (new \app\common\model\Orders())->where([
            'house_id' => $id,
            'pay_status' => 1,
            'user_id' => $this->auth->id,
            'house_type' => 'findstore'
        ])->find();
        if ($order_row) {
            $this->error('请先退费');
        }
        $result = \app\common\model\Findstore::where(['id' => $id, 'user_id' => $this->auth->id])->delete();
        (new UserCollect())->where([
            'type'=>'rent',
            'houses_id'=>$id
        ])->delete();
        if ($result) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    #[
        Apidoc\Title("找店详情获取编辑信息"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/findstore/detail"),
        Apidoc\Query(name: "id", type: "number", require: true, desc: "找店ID", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
        Apidoc\Returned("pay_status", type: "int", desc: "支付状态"),
        Apidoc\Returned("pay_status_text", type: "string", desc: "支付状态:0=待支付,1=支付成功,2=已退款"),
        Apidoc\Returned("payed_day", type: "支付天数", desc: "默认0"),
    ]
    public function detail()
    {
        $id = $this->request->get('id');
        $result = \app\common\model\Findstore::where(['id' => $id, 'user_id' => $this->auth->id])->order('id', 'desc')->find();
        if (!$result) {
            $this->error('找不到数据');
        }
        $order_row = (new \app\common\model\Orders())->where([
            'house_id' => $id,
            'user_id' => $this->auth->id,
            'house_type' => 'findstore'
        ])->find();
        $result['pay_status'] = $order_row ? $order_row['pay_status'] : 0;//支付状态:0=待支付,1=支付成功,2=已退款

        if ($order_row) {
            $result['payed_day'] = (time() - $order_row['paid_time']) / (3600 * 24);
        } else {
            $result['payed_day'] = 0;
        }
        $result['dealer_info'] = '';
        if ($result['status'] == 4) {
            $dealer_id = (new \app\admin\model\Orders())
                ->where('id', $result['order_id'])
//                ->where([
//                    'house_id' => $result['id'],
//                    'pay_status' => ['in', [1,3]],
//                    'house_type' => 'findstore'
//                ])
                ->value('to_uid');
            $result['dealer_info'] = (new \app\admin\model\User())->where(['id' => $dealer_id])->find();
        }
        if ($result) {
            $this->success('获取成功', $result);
        } else {
            $this->error('获取失败');
        }
    }

    #[
        Apidoc\Title("导入找店铺"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/Findstore/import"),
        Apidoc\Param(name: "file", type: "string", require: true, desc: "上传文件路径", mock: "/templates/findstore_template.xlsx"),
    ]
    public function import(): void
    {
        set_time_limit(0);
        ob_clean();
        $file = $this->request->post('file');
        if (empty($file)) {
            $this->error('请选择上传的文件');
        }
        $ext = pathinfo($file, PATHINFO_EXTENSION);//后缀
        if (!in_array($ext, ['xls', 'xlsx'])) {
            $this->error('不支持此类型文件');
        }
        if ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        $filePath = App::getRootPath() . 'public' . DIRECTORY_SEPARATOR . $file;
        $data = [];
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load($filePath);
        $sheet = $spreadsheet->getActiveSheet();
        $highestRow = $sheet->getHighestRow();
        $allColumn = $sheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $sheet->getHighestRow(); //取得一共有多少行
        $highestColumnIndex = Coordinate::columnIndexFromString($allColumn);//最大列转换成数字
        $fileds = [
            '',
            'name',
            'start_area',
            'end_area',
            'start_rent',
            'end_rent',
            'rent_unit',
            'reward',
//            'city',
//            'introduction',
//            'address'
        ];
        $model = new  \app\common\model\Findstore();
        $field_count = count($fileds);
        for ($row = 2; $row <= $highestRow; $row++) {
            // 构建默认字段数据
            $arr_value = [
                'create_time' => time(),
                'update_time' => time(),
            ];
            for ($col = 1; $col <= $field_count - 1; $col++) {
                // 'A' 对应的ASCII码十进制为 64
                // 将ASCII值转为字符
                $chr = $this->getColumnZimu($col);
                // 列转为数据库字段名
                $key = $fileds[$col] ?? $chr;
                $value = $sheet->getCell($chr . $row)->getValue();
                $value = trim($value);
                // 构建当前行数据
                $arr_value[$key] = $value;
            }
            $arr_value['user_id'] = $this->auth->id;
            $data[] = $arr_value;
        }
        $result = $model->saveAll($data);
        if ($result) {
            $this->success('导入成功' . count($data) . '条数据', $data);
        } else {
            $this->error('导入失败', $data);
        }
    }

    private function getColumnZimu($num)
    {
        if ($num >= 0 && $num < 26) {
            // 如果是 A 到 Z 之间的列，直接返回对应的字母
            return chr(65 + $num);
        } else {
            // 针对 AA、AB、AC ... ZZ 这样的列，使用类似递归的方式计算出对应的字母组合
            $result = '';
            while ($num >= 26) {
                $result .= chr(65 + ($num % 26));
                $num = intval($num / 26) - 1;
            }
            $result .= chr(65 + $num);
            return strrev($result); // 需要反转列名字母组合
        }
    }

}
